package tt.dz.appserver.util;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import org.apache.commons.codec.digest.DigestUtils;
import org.apache.log4j.Logger;

import com.alibaba.fastjson.JSONObject;

import tt.dz.appserver.entity.vo.JSSign;
import tt.dz.appserver.entity.vo.WeiXinOrderInfoVo;
import tt.dz.appserver.util.http.HttpUtils;

public class WeiXinUtils {

	
	private static final Logger LOG = Logger.getLogger("[微信基础方法]:");
	
	public	static	final	String	MD5="MD5";
	public	static	final	String	SHA1="SHA1";
	
	public static JSONObject getAccountAccessToken(String resoure, String merchantCode,String code) {
		
		
		 Map<String, String> basicMap=getBasicMessage(resoure,merchantCode);
		 
		 // 获取键 值
		 Map<String, String> paramMap= new HashMap<String, String>();
		 paramMap.put("appid", basicMap.get("WeixinApiKey"));
		 paramMap.put("secret", basicMap.get("WeixinSecret"));
		 LOG.info("appid=["+basicMap.get("WeixinApiKey")+"],secret=["+ basicMap.get("WeixinSecret")+"]");
		 paramMap.put("code", code);
		 paramMap.put("grant_type", "authorization_code");

		String accountBasic = HttpUtils.getRequest(Constants.weixinUrl.WEIXIN_GET_THRID_TOKEN, paramMap);
		
		JSONObject  accountBasicJSON=JSONObject.parseObject(accountBasic);
		return accountBasicJSON;
	}
	/**
	 * 获取用户基本信息
	 * @param access_token
	 * @param openid
	 * @param lang
	 * @return
	 */
	public static JSONObject getTridUserinfo(String access_token, String openid,String lang) {
		
		 
		 Map<String, String> paramMap= new HashMap<String, String>();
		 paramMap.put("access_token", access_token);
		 paramMap.put("openid", openid);
		 paramMap.put("lang", lang);

		String accountBasic = HttpUtils.getRequest(Constants.weixinUrl.WEIXIN_USERINFO, paramMap);
		
		JSONObject  accountBasicJSON=JSONObject.parseObject(accountBasic);
		return accountBasicJSON;
	}
	/**
	 * 验证用户token是否有效
	 * @param access_token
	 * @param openid
	 * @return
	 */
	public static JSONObject validToken(String access_token, String openid) {
			 
		 Map<String, String> paramMap= new HashMap<String, String>();
		 paramMap.put("access_token", access_token);
		 paramMap.put("openid", openid);

		String accountBasic = HttpUtils.getRequest(Constants.weixinUrl.WEIXIN_VALID_TOKEN, paramMap);
		LOG.info("验证用户token是否有效返回结果"+accountBasic);
		JSONObject  accountBasicJSON=JSONObject.parseObject(accountBasic);
		return accountBasicJSON;
	}
	
	/**
	 * 配置文件读取数据 
	 * @param resoure
	 * @param merchantCode
	 * @return
	 */
	public static Map<String, String> getBasicMessage(String resoure, String merchantCode) {
		
		 Map<String, String> paramMap= new HashMap<String, String>();
		 
		 if(ConverUtil.checkDataSource(resoure, merchantCode)==1){
			 /** 华体应用id,秘钥*/
			 paramMap.put("WeixinApiKey", Constants.huatiWeixinApiKey);
			 paramMap.put("WeixinSecret", Constants.huatiWeixinSecret);
			 paramMap.put("WeixinPayKey", Constants.huatiWeixinPayKey);
			 paramMap.put("WeixinPayNum", Constants.huatiWeixinPayNum);
		 }else{
			 /**电桩 基本信息**/
			 paramMap.put("WeixinApiKey", Constants.dianzhuangWeixinApiKey);
			 paramMap.put("WeixinSecret", Constants.dianzhuangWeixinSecret);
			 paramMap.put("WeixinPayKey", Constants.dianzhuangWeixinApiKey);
			 paramMap.put("WeixinPayNum", Constants.dianzhuangWeixinPayNum);
		 }

		 LOG.info("WeixinApiKey="+paramMap.get("WeixinApiKey")+";WeixinSecret=" 
				 +paramMap.get("WeixinSecret")+";WeixinPayKey="+paramMap.get("WeixinPayKey")+";WeixinPayNum="+
				 paramMap.get("WeixinPayNum"));
		 
		return paramMap;

	}
	
	/**
	 *  生成js签名算法
	 * @param object
	 * @param resoure
	 * @param merchantCode
	 * @return
	 */
	public static JSSign getJsSign(String resoure,String merchantCode,String signType,String url){
		JSSign jsSign=new JSSign();
		
		jsSign.setSignType(signType);
		jsSign.setTimeStamp(Long.toString(new Date().getTime()/1000));
		jsSign.setTimestamp(jsSign.getTimeStamp());
		jsSign.setNonceStr(StringUtils.getRandomString(16));
		String jsapi_ticket=RefreshUtil.getJSTicket(resoure, merchantCode,jsSign);
		if(jsapi_ticket==""){
			LOG.error("签名算法获取jsapi_ticket失败");
			return null;
		}
		jsSign.setJsapi_ticket(jsapi_ticket);
		jsSign.setUrl(url);
		StringBuffer sb= new StringBuffer();
		sb.append("jsapi_ticket=").append(jsSign.getJsapi_ticket());
		sb.append("&noncestr=").append(jsSign.getNonceStr());
		
		//md5 与sha1 参数不同
		if(signType.equals(MD5)){
			sb.append("&timestamp=");
		}else{
			sb.append("&timestamp=");
		}
		sb.append(jsSign.getTimeStamp()).append("&url=").append(url);
		LOG.info("算法签名原字符串："+sb.toString());
		if(signType.equals(MD5)){
			jsSign.setSign(DigestUtils.md5Hex(sb.toString()));		
		}else{
			jsSign.setSign(DigestUtils.shaHex(sb.toString()));
		}	
		LOG.info("算法生成的签名："+jsSign.getSign());
		return jsSign;
	}
	
	public static WeiXinOrderInfoVo getOrderSign(WeiXinOrderInfoVo vo, String source, String merchantCode){
		
		StringBuffer sb = new StringBuffer();
		Map<String,String> map= getBasicMessage(source, merchantCode);
		//1.appid 必填
		sb.append("appid").append(map.get("WeixinApiKey"));
		//attach
		if(vo.getAttach()!=null&&(!vo.getAttach().equals(""))){
			sb.append("attach").append(vo.getAttach());
		}
		//body 必填
		sb.append("body").append(vo.getBody());
		//device_info 设备号
		if(vo.getDevice_info()!=null&&!vo.getDevice_info().equals("")){
			sb.append("device_info").append(vo.getDevice_info());
		}
		// fee_type 默认人民币 
		sb.append("fee_type").append(vo.getFee_type());
		if(vo.getGoods_tag()!=null&&(!vo.getGoods_tag().equals(""))){
			sb.append("goods_tag").append(vo.getGoods_tag());
		}
		//limit_pay 
		if(vo.getLimit_pay()!=null&&(!vo.getLimit_pay().equals(""))){
			sb.append("limit_pay").append(vo.getLimit_pay());
		}
		// mch_id 商户id
		sb.append("mch_id").append(map.get("WeixinPayNum"));
		sb.append("nonce_str").append(vo.getNonce_str());
		sb.append("notify_url").append(vo.getNotify_url());
		
		if(vo.getOpenid()!=null&&(!vo.getOpenid().equals(""))){
			sb.append("openid").append(vo.getOpenid());
		}
		//订单号
		sb.append("out_trade_no").append(vo.getOut_trade_no());
		if(vo.getProduct_id()!=null&&(!vo.getProduct_id().equals(""))){
			sb.append("product_id").append(vo.getProduct_id());
		}
		//账单发起ip
		sb.append("spbill_create_ip").append(vo.getSpbill_create_ip());
		if(vo.getTime_expire()!=null&&(!vo.getTime_expire().equals(""))){
			sb.append("time_expire").append(vo.getTime_expire());
		}
		if(vo.getTime_start()!=null&&(!vo.getTime_start().equals(""))){
			sb.append("time_start").append(vo.getTime_start());
		}
		sb.append("total_fee").append(vo.getTotal_fee()+"");
		sb.append("trade_type").append(vo.getTrade_type());
		sb.append("key").append(map.get("WeixinPayKey"));
		LOG.info("拼接的json数据为="+sb.toString());
		String sign=DigestUtils.md5Hex(sb.toString()).toUpperCase();
		LOG.info("生成的签名sign="+sign);
		vo.setSign(sign);
		return vo;
	}
	
	public static String payUnifiedorder(WeiXinOrderInfoVo vo, String source, 
			String merchantCode){
		
		Map<String,String> paramMap= new HashMap<String,String>();
		paramMap.put("appid", vo.getAppid());
		paramMap.put("mch_id", vo.getMch_id());
		paramMap.put("device_info", vo.getDevice_info());
		paramMap.put("nonce_str", vo.getNonce_str());
		paramMap.put("sign", vo.getSign());
		paramMap.put("body", vo.getBody());
		paramMap.put("attach", vo.getAttach());
		paramMap.put("out_trade_no", vo.getOut_trade_no());
		paramMap.put("fee_type", vo.getFee_type());
		paramMap.put("total_fee", vo.getTotal_fee()+"");
		paramMap.put("spbill_create_ip", vo.getSpbill_create_ip());
		paramMap.put("time_start", vo.getTime_start());
		paramMap.put("time_expire", vo.getTime_expire());
		paramMap.put("goods_tag", vo.getGoods_tag());
		paramMap.put("notify_url", vo.getNotify_url());
		paramMap.put("trade_type", vo.getTrade_type());
		paramMap.put("product_id", vo.getProduct_id());
		paramMap.put("limit_pay", vo.getLimit_pay());
		paramMap.put("openid", vo.getOpenid());
		
		String  str= HttpUtils.postRequest(Constants.weixinUrl.WEIXIN_ORDER, paramMap,true);
		LOG.info("访问微信下单，返回的接口"+str);
		return str;
	}
	
	public static boolean  checkWeixOrder(WeiXinOrderInfoVo vo,String source,String merchantCode){
			
		return false;
	}	

}
